const cryptoJS = require("crypto-js");
const CryptoKey = require("../config/signConfig").CryptoKey;
const key = cryptoJS.enc.Utf8.parse(CryptoKey);
/* Crypto加密方法
 * @param {object} _data       对用户请求后端的参数进行加密
 */
const setCrypto = (_data) => {
  let data = {
    t: new Date().getTime(), //时间戳
    ..._data,
  };
  let encrypted = cryptoJS.AES.encrypt(JSON.stringify(data), key, {
    mode: cryptoJS.mode.ECB,
    padding: cryptoJS.pad.Pkcs7,
  });
  return encrypted.toString();
};
/* Crypto解密方法
 * @param {string} _token       将秘文解密成对象形式
 */
const getCrypto = (_token) => {
  _token = decodeURIComponent(_token); //前端传参有特殊字符（中文）时转义（替换百分号）
  let decrypt = cryptoJS.AES.decrypt(_token, key, {
    mode: cryptoJS.mode.ECB,
    padding: cryptoJS.pad.Pkcs7,
  });
  return JSON.parse(cryptoJS.enc.Utf8.stringify(decrypt).toString());
};
module.exports = {
  setCrypto,
  getCrypto,
};
